const DS = require('dsbridge')

const global = {
    getUrlName (name) {
        var r = new RegExp('(\\?|#|&)' + name + '=([^&#]*)(&|#|$)')
        var m = location.href.match(r)
        return decodeURIComponent(!m ? '' : m[2])
    },
    isInApp () {
        let str = DS.hasNativeMethod('DS.getToken')
        return str
    },
    getToken () {
        return new Promise((resolve, reject) => {
            DS.call('DS.getToken', {}, (v) => {
                resolve(v)
            })
        })
    },
    // 获取配置信息
    getClientAppState () {
        return new Promise((resolve, reject) => {
            DS.call(`DS.getClientAppState`, {}, (v) => {
                resolve(v)
            })
        })
    },
    scrollTop () {
        let timer = setInterval(() => {
            let scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            let ispeed = Math.floor(-scrollTop / 5)
            document.documentElement.scrollTop = document.body.scrollTop = scrollTop + ispeed
            if (scrollTop === 0) {
                clearInterval(timer)
            }
        })
    },
    setHeader (params) {
        DS.call('DS.setHeader', {
            native_headershow: params.native_headershow, // 1 显示原生titlebar，其他不显示
            statusBarAppearance: params.statusBarAppearance, // 沉浸式
            titleName: params.titleName, // 标题栏的名字
            top_link_image: params.top_link_image, // 图片背景链接
            topstyle: params.topstyle, // topimg 图片 topcolor 颜色背景
            native_top_words_color: params.native_top_words_color, // 文字颜色
            str_link_color: params.str_link_color, // 颜色背景渐变色开始色
            end_link_color: params.end_link_color, // 颜色背景渐变色结束色
            hideBottom: params.hideBottom, // 底部状态栏
            isHideCloseBt: params.hideCloseBtn, // 是否隐藏关闭按钮 0，不隐藏，1隐藏
            isBounceEnabled: params.BounceEnabled // ios 页面弹动 1 可弹动 0 禁止弹动

        })
    },
    openPage (name, pageParam, call) {
        pageParam = (pageParam === null || pageParam === '' || typeof (pageParam) === 'undefined') ? {} : pageParam
        DS.call('DS.openPage', {
            page: name,
            params: pageParam
        }, (ret) => {
            call(ret)
        })
    },
    closePage () {
        DS.call('DS.closePage')
    },
    setTitle (title) {
        document.title = title
        if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
            var i = document.createElement('iframe')
            i.src = '/favicon.ico'
            i.style.display = 'none'
            i.onload = () => {
                setTimeout(() => {
                    i.remove()
                }, 9)
            }
            document.body.appendChild(i)
        }
    },
    // 数据转化
    formatNumber: function (n) {
        return n > 9 ? n : '0' + n
    },
    // 时间戳格式化
    // Y/M/D h:m:s
    formatTime: function (number, format) {
        var formateArr = ['Y', 'M', 'D', 'h', 'm', 's']
        var returnArr = []
        var date = new Date(number * 1000)

        returnArr.push(date.getFullYear())
        returnArr.push(this.formatNumber(date.getMonth() + 1))
        returnArr.push(this.formatNumber(date.getDate()))

        returnArr.push(this.formatNumber(date.getHours()))
        returnArr.push(this.formatNumber(date.getMinutes()))
        returnArr.push(this.formatNumber(date.getSeconds()))

        for (var i in returnArr) {
            format = format.replace(formateArr[i], returnArr[i])
        }
        return format
    },
    // 判断时间
    getDateDiff: function (dateTimeStamp) {
        var result = ''
        var minute = 1000 * 60
        var hour = minute * 60
        var day = hour * 24
        var month = day * 30
        var now = new Date().getTime()
        var diffValue = now - dateTimeStamp
        if (diffValue < 0) return
        var monthC = diffValue / month
        var weekC = diffValue / (7 * day)
        var dayC = diffValue / day
        var hourC = diffValue / hour
        var minC = diffValue / minute

        if (monthC >= 1) {
            result = '' + parseInt(monthC) + '月前'
        } else if (weekC >= 1) {
            result = '' + parseInt(weekC) + '周前'
        } else if (dayC >= 1) {
            result = '' + parseInt(dayC) + '天前'
        } else if (hourC >= 1) {
            result = '' + parseInt(hourC) + '小时前'
        } else if (minC >= 1) {
            result = '' + parseInt(minC) + '分钟前'
        } else {
            result = '刚刚'
        }
        return result
    },
    getTimeArray: function (time) {

    },
    formatDate: function (time) {
        time = parseInt(time / 1000)
        let result = this.formatTime(time, 'Y-M-D h:m:s')
        return result
    },
    // 判断昨天
    isYesterday: function (time) {
        let date = new Date(time)
        let nowDay = new Date()
        if (date.getFullYear() == nowDay.getFullYear() && date.getMonth() == nowDay.getMonth()) { // 同年同月
            let diff = nowDay.getDate() - date.getDate()
            return diff === 1
        } else {
            return false
        }
    },
    // 判断今年
    isYear: function (timeValue) {
        let dateYear = new Date(timeValue).getFullYear()
        let nowYear = new Date().getFullYear()
        if (dateYear == nowYear) {
            return true
        } else {
            return false
        }
    },
    // 获取星期N
    getWeek: function (date) {
        let weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        let week = weekArr[new Date(date).getDay()]
        return week
    },
    // 处理消息详情页时间（仿微信）
    resolveTimeFormat: function (timeValue) {
        timeValue = new Date(timeValue * 1000).getTime()
        var timeNew = new Date().getTime() // 当前时间
        var timeDiffer = timeNew - timeValue // 两者时间差
        var returnTime = ''
        if (timeDiffer < 86400000 && this.isYesterday(timeValue) === false) { // 今天
            returnTime = this.formatDate(timeValue).substr(11, 5)
        } else if (timeDiffer > 3600000 && this.isYesterday(timeValue) === true) { // 昨天
            returnTime = '昨天 ' + this.formatDate(timeValue).substr(11, 5)
        } else if (timeDiffer > 86400000 && timeDiffer <= 518400000) { // 近6天-》星期N
            returnTime = this.getWeek(timeValue) + ' ' + this.formatDate(timeValue).substr(11, 5)
        } else if (timeDiffer > 86400000 && this.isYesterday(timeValue) === false && this.isYear(timeValue) === true) { // 今年
            returnTime = this.formatDate(timeValue).substr(5, 11)
        } else if (timeDiffer > 86400000 && this.isYesterday(timeValue) === false && this.isYear(timeValue) === false) { // 往年
            returnTime = this.formatDate(timeValue).substr(0, 16)
        }
        return returnTime
    },
    // 获取app系统，版本等信息
    compareVersion (v1, v2) {
        v1 = v1.split('.')
        v2 = v2.split('.')
        const len = Math.max(v1.length, v2.length)
        // 调整两个版本号位数相同
        while (v1.length < len) {
            v1.push('0')
        }
        while (v2.length < len) {
            v2.push('0')
        }
        // 循环判断每位数的大小
        for (let i = 0; i < len; i++) {
            const num1 = parseInt(v1[i])
            const num2 = parseInt(v2[i])
            if (num1 > num2) {
                return 1
            } else if (num1 < num2) {
                return -1
            }
        }
        return 0
    },
    // 深度克隆对象
    deepClone (target) {
        let result
        if (typeof target === 'object') {
            if (Array.isArray(target)) {
                result = []
                for (const i in target) {
                    result.push(this.deepClone(target[i]))
                }
            } else if (target === null) {
                result = null
            } else if (target.constructor === RegExp) {
                result = target
            } else {
                result = {}
                for (const i in target) {
                    result[i] = this.deepClone(target[i])
                }
            }
        } else {
            result = target
        }
        return result
    }

}

export default global
